package com.pay.game.central.web.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.uuid.Generators;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.pay.game.central.common.Result;
import com.pay.game.central.common.ResultGenerator;
import com.pay.game.central.security.annotaion.UserLoginToken;
import com.pay.game.central.web.bean.PddCustomer;
import com.pay.game.central.web.service.CustomerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("customer")
public class CustomerController {

    @Autowired
    private CustomerService customerService;

    @GetMapping("/list")
    @ResponseBody
    @UserLoginToken
    Result<PageInfo<PddCustomer>> list(@RequestParam(defaultValue = "1") int page,
                                       @RequestParam(defaultValue = "20") int limit,
                                       String tel, int status){
        PageHelper.startPage(page,limit);
        return ResultGenerator.genSuccessResult(new PageInfo<>(customerService.list(tel,status)));
    }


    /**
     * 导入Excel
     * @param body
     * @return
     */
    @PostMapping("/import")
    @ResponseBody
    @UserLoginToken
    Result<String> importCustomer(@RequestBody String body){
        JSONArray array = JSON.parseArray(body);
        int time = (int) (System.currentTimeMillis()/1000);
        List<PddCustomer> all = array.stream().map(obj->{
            JSONObject object = (JSONObject) obj;
            PddCustomer pddStore = new PddCustomer();
            pddStore.setId(Generators.timeBasedGenerator().generate().toString());
            pddStore.setTel(object.getString("手机号").trim());
            pddStore.setCreate_time(time);
            return pddStore;
        }).collect(Collectors.toList());
        List<String> tels =  customerService.allTel();
        if (tels == null) tels = new ArrayList<>();
        List<String> finalTels = tels;
        //过滤重复手机号
        List<PddCustomer> customers = all.stream()
                .filter(item-> !finalTels.contains(item.getTel())).collect(Collectors.toList())
                .stream().distinct().collect(Collectors.toList());
        if (customers.size() > 0) customerService.addCustomers(customers);
        return ResultGenerator.genSuccessResult("导入成功");
    }


}
